﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

public class Solution56
{
    public int Mycompare(int[]a, int[] b)
    {
        
        return a[0].CompareTo(b[0]);

    }
   

    public int[][] Merge(int[][] intervals)
    {

        IList<IList<int>> result = new List<IList<int>>();
        Array.Sort(intervals , Mycompare);
        //if(a[0]>b[0],return true;


        for (int i = 1; i < intervals.Length; i++)
        {

            int[] pre = intervals[i - 1];
            int[] cur = intervals[i];
            int[] newInte = new int[pre.Length];
            if (cur[0] <= pre[1])
            {
                newInte[0] = Math.Min(cur[0], pre[0]);
                newInte[1] = Math.Max(cur[1], pre[1]);
                intervals[i] = newInte;

            }//合并
            else
            {
                IList<int> path = new List<int>(pre);
                result.Add(path);
            }

        }
        IList<int> last = new List<int>(intervals[intervals.Length - 1]);
        result.Add(last);


        int[][] res = new int[result.Count][];

        for (int i = 0; i < result.Count; i++)
        {

            res[i] = result[i].ToArray();


        }
        return res;


    }
}


class Program56
{

    static void Main56()
    {
        Solution56 solution = new Solution56();
        int[][] intervals = [[1, 3], [2, 6], [8, 10], [15, 18]];
        int[][] res = solution.Merge(intervals);

        for (int i = 0; i < res.Length; i++) {


            for (int j = 0; j < res[i].Length; j++)
            {
                Console.Write(res[i][j]+",");
            }
            Console.WriteLine();
        }

    }
}